/**
 * 高德地图WeChat SDK适配器
 * 将AMapWX的SDK接口适配为与现有amap.js工具相同的接口
 */

// 直接导入AMapWX对象
// 注意：在微信小程序中，require引用可以省略.js后缀
const AMapWX = require('../libs/amap-wx');

// 高德地图Key
const AMAP_KEY = '341dbca57f8782a04a2e9ed52d2f600d';

// 初始化AMapWX实例
const amapInstance = new AMapWX({
  key: AMAP_KEY
});

/**
 * 获取当前位置
 * @returns {Promise<{latitude: number, longitude: number}>} 
 */
function getCurrentLocation() {
  return new Promise((resolve, reject) => {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        resolve({
          latitude: res.latitude,
          longitude: res.longitude
        });
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

/**
 * 搜索附近POI
 * @param {Object} options 
 * @param {Object} options.location - 当前位置
 * @param {number} options.location.latitude - 纬度
 * @param {number} options.location.longitude - 经度
 * @param {string} options.type - POI类型代码
 * @param {number} options.radius - 搜索半径（米）
 * @param {number} options.limit - 返回结果数量限制
 * @returns {Promise<Array>} - POI列表
 */
function searchNearby(options = {}) {
  const { location, type, radius = 2000, limit = 20 } = options;
  
  if (!location) {
    return Promise.reject(new Error('Missing location parameter'));
  }
  
  return new Promise((resolve, reject) => {
    amapInstance.getPoiAround({
      querytypes: type, // POI类型代码
      location: `${location.longitude},${location.latitude}`, // 经度,纬度
      querykeywords: '', // 关键词
      success: (data) => {
        if (data && data.markers) {
          // 转换为统一的POI对象格式
          const pois = data.markers.map(item => ({
            id: item.id,
            name: item.name,
            latitude: item.latitude,
            longitude: item.longitude,
            address: item.address || '',
            type: item.type || '',
            distance: item.distance || 0
          }));
          resolve(pois);
        } else {
          resolve([]);
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

/**
 * 计算路线
 * @param {Object} options 
 * @param {Object} options.origin - 起点位置
 * @param {Object} options.destination - 终点位置
 * @param {string} options.mode - 出行方式: driving(驾车)、walking(步行)、transit(公交)、riding(骑行)
 * @returns {Promise<Object>} - 路线信息
 */
function calculateRoute(options = {}) {
  const { origin, destination, mode = 'walking' } = options;
  
  if (!origin || !destination) {
    return Promise.reject(new Error('Missing origin or destination'));
  }
  
  return new Promise((resolve, reject) => {
    const methodMap = {
      driving: 'getDrivingRoute',
      walking: 'getWalkingRoute',
      transit: 'getTransitRoute',
      riding: 'getRidingRoute'
    };
    
    const method = methodMap[mode] || 'getWalkingRoute';
    
    amapInstance[method]({
      origin: `${origin.longitude},${origin.latitude}`,
      destination: `${destination.longitude},${destination.latitude}`,
      success: (data) => {
        if (data && data.paths && data.paths.length > 0) {
          const route = data.paths[0];
          resolve({
            distance: route.distance,
            duration: route.duration,
            // 如果需要，可以添加更多数据
            polyline: data.polyline || []
          });
        } else {
          resolve({
            distance: 0,
            duration: 0,
            polyline: []
          });
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

/**
 * 逆向地理编码（坐标转地址）
 * @param {number} latitude - 纬度
 * @param {number} longitude - 经度
 * @returns {Promise<Object>} - 地址信息
 */
function reverseGeocode(latitude, longitude) {
  return new Promise((resolve, reject) => {
    amapInstance.getRegeo({
      location: `${longitude},${latitude}`,
      success: (data) => {
        if (data && data.length > 0) {
          const result = data[0];
          resolve({
            address: result.desc || result.regeocodeData.formatted_address,
            name: result.name || '',
            district: result.regeocodeData.addressComponent.district || '',
            city: result.regeocodeData.addressComponent.city || '',
            province: result.regeocodeData.addressComponent.province || ''
          });
        } else {
          resolve(null);
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

module.exports = {
  getCurrentLocation,
  searchNearby,
  calculateRoute,
  reverseGeocode
};

/**
 * 打开微信内置地图导航
 * @param {Object} options 导航选项
 * @param {String} options.name 目的地名称
 * @param {Number} options.latitude 目的地纬度
 * @param {Number} options.longitude 目的地经度
 * @param {String} options.address 目的地地址
 * @returns {Promise} Promise对象
 */
export function openMapApp(options) {
  if (!options.latitude || !options.longitude) {
    return Promise.reject(new Error('目的地坐标不能为空'));
  }
  
  return new Promise((resolve, reject) => {
    wx.openLocation({
      latitude: options.latitude,
      longitude: options.longitude,
      name: options.name || '目的地',
      address: options.address || '',
      scale: 18,
      success: () => {
        resolve();
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
} 